function random(min, max) {
    return min + Math.random() * (max - min)
}

function randomInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min)
}



class Concurrent {
    constructor(n) {
        this.size = n
        this.queque = []
        this.workingNum = 0
    }

    add(task) {
        this.queque.push(task)
        if (this.size > this.workingNum) {
            this.doNext()
        }
    }
    doNext() {
        if (this.queque.length && this.workingNum < this.size) {
            this.workingNum++
            const fn = this.queque.shift()
            Promise.resolve(fn())
                .then(() => {
                    this.workingNum--
                    this.doNext()
                }).catch(() => {
                    this.workingNum--
                    this.doNext()
                })
        }
    }
}

const timeout = time => new Promise((resolve) => {
    setTimeout(resolve, time)
})

const schedule = new Concurrent(2);

const addTask = (time, order) => {
    schedule.add(() => timeout(time).then(() => {
        console.log(order);
    }))
}

addTask(1000, 1)
addTask(500, 2)
addTask(300, 3)
addTask(400, 4)

